package com.sly.netty.netty;

import cn.hutool.json.JSONUtil;
import com.sly.netty.core.Message;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

/**
 * netty 客户端
 *
 * @author SLY
 * @date 2025/2/24
 */
@Slf4j
public class NettyClient01 {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup(1);
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //向pipeline加入解码器
                            pipeline.addLast("decoder", new StringDecoder());
                            //向pipeline加入编码器
                            pipeline.addLast("encoder", new StringEncoder());
                            //加入自己的业务处理handler
                            pipeline.addLast(new NettyClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9100).sync();
            //得到 channel
            Channel channel = channelFuture.channel();
            log.info("========{}========", channel.localAddress());
            //客户端需要输入信息， 创建一个扫描器
            Message message = new Message();
            message.setContent("上线了");
            message.setFromUser("1");
            message.setToUser("1");
            channel.writeAndFlush(JSONUtil.toJsonStr(message));
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                //通过 channel 发送到服务器端
                message.setContent(msg);
                message.setToUser("2");
                channel.writeAndFlush(JSONUtil.toJsonStr(message));
            }
        } finally {
            group.shutdownGracefully();
        }
    }
}
